<template>
    <div class="user-info-container">
        <div class="page-header">
            <h1 class="page-title">个人信息</h1>
            <p class="page-subtitle">管理您的个人资料和账户设置</p>
        </div>

        <div class="info-card">
            <div class="card-header">
                <div class="avatar-section">
                    <el-upload class="avatar-uploader" :action="updateAvatar().url" :method="updateAvatar().method"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                        :headers="{
                            'Authorization': 'Bearer ' + user_store.token
                        }">
                        <el-avatar :size="120" :src="user.avatar ? '/file'+user.avatar : ''" class="user-avatar">
                            <el-icon>
                                <User />
                            </el-icon>
                        </el-avatar>
                    </el-upload>
                    <div class="upload-hint">点击头像更换</div>
                </div>

                <div class="user-summary">
                    <h2 class="username">{{ user.username }}</h2>
                    <div class="user-stats">
                        <div class="stat-item">
                            <span class="stat-label">加入时间</span>
                            <span class="stat-value">{{ formatDate(user.created_at) }}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">性别</span>
                            <span class="stat-value">{{ user.sex === 1 ? '男' : '女' }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card-body">
                <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px" class="user-form">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="userForm.username" :disabled="true" class="form-input" />
                    </el-form-item>

                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="userForm.email" type="email" class="form-input" />
                    </el-form-item>

                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="userForm.phone" class="form-input" />
                    </el-form-item>

                    <el-form-item label="性别" prop="sex">
                        <el-radio-group v-model="userForm.sex">
                            <el-radio :label="0">女</el-radio>
                            <el-radio :label="1">男</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="生日" prop="birthday">
                        <el-date-picker v-model="userForm.birthday" value-format="YYYY-MM-DD" type="date"
                            placeholder="请选择日期" class="form-input" />
                    </el-form-item>

                    <el-form-item label="个人简介" prop="intro">
                        <el-input v-model="userForm.intro" type="textarea" rows="4" placeholder="介绍一下自己..."
                            class="form-input" />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="updateUserInfo" :loading="loading" class="submit-btn">
                            保存更改
                        </el-button>
                        <el-button @click="resetForm">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <!-- 修改密码卡片 -->
        <div class="password-card">
            <div class="card-header">
                <h3 class="card-title">修改密码</h3>
                <p class="card-subtitle">为了账户安全，请定期更换密码</p>
            </div>

            <div class="card-body">
                <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px"
                    class="password-form">
                    <el-form-item label="原密码" prop="oldPassword">
                        <el-input v-model="passwordForm.oldPassword" type="password" show-password class="form-input" />
                    </el-form-item>

                    <el-form-item label="新密码" prop="newPassword">
                        <el-input v-model="passwordForm.newPassword" type="password" show-password class="form-input" />
                    </el-form-item>

                    <el-form-item label="确认密码" prop="confirmPassword">
                        <el-input v-model="passwordForm.confirmPassword" type="password" show-password
                            class="form-input" />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="updatePassword" :loading="passwordLoading" class="submit-btn">
                            修改密码
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { User, Upload } from '@element-plus/icons-vue'
import { getUser, updateUser, updateUserPassword, updateAvatar } from '@/api/user'
import { userStore } from '@/store/user'

const userFormRef = ref()
const passwordFormRef = ref()
const loading = ref(false)
const passwordLoading = ref(false)
const user_store = userStore()
const router = useRouter()

const user = ref({
    username: '',
    email: '',
    phone: '',
    sex: 0,
    birthday: '',
    bio: '',
    avatar: '',
    created_at: ''
})

const userForm = reactive({
    username: '',
    email: '',
    phone: '',
    sex: 0,
    birthday: '',
    intro: '',
    avatar: ''
})

const passwordForm = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})

const rules = reactive({
    email: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ]
})

const passwordRules = reactive({
    oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能低于6位', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== passwordForm.newPassword) {
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
})

// 获取用户信息
const fetchUserInfo = async () => {
    try {
        const data = await getUser()
        user.value = data

        // 填充表单
        userForm.username = data.username || ''
        userForm.email = data.email || ''
        userForm.phone = data.phone || ''
        userForm.sex = data.sex || 0
        userForm.birthday = data.birthday || ''
        userForm.intro = data.intro || ''
        userForm.avatar = data.avatar || ''

    } catch (error) {
        console.error('获取用户信息失败:', error)
        ElMessage.error('获取用户信息失败')
    }
}

// 更新用户信息
const updateUserInfo = async () => {
    if (!userFormRef.value) return

    loading.value = true

    try {
        await userFormRef.value.validate()
        const filteredData = filterEmptyValues(userForm)
        await updateUser(filteredData)

        ElMessage.success('用户信息更新成功')
        fetchUserInfo()

    } catch (error) {
        console.error('更新用户信息失败:', error)
        if (error.response && error.response.data) {
            const data = error.response.data
            for (let key in data) {
                ElMessage.error(data[key][0] || '更新失败')
            }
        } else {
            ElMessage.error('更新用户信息失败')
        }
    } finally {
        loading.value = false
    }
}

// 过滤空值的辅助函数
const filterEmptyValues = (obj) => {
    const filtered = {}
    for (let key in obj) {
        const value = obj[key]
        // 排除avatar字段，因为头像通过单独的文件上传接口处理
        if (key === 'avatar') continue
        // 保留数字（包括0）和非空字符串，过滤掉null、undefined和空字符串
        if (value !== null && value !== undefined) {
            if (typeof value === 'number' || value !== '') {
                filtered[key] = value
            }
        }
    }
    return filtered
}



// 修改密码
const updatePassword = async () => {
    if (!passwordFormRef.value) return

    passwordLoading.value = true

    try {
        await passwordFormRef.value.validate()
        await updateUserPassword({
            password: passwordForm.oldPassword,
            new_password: passwordForm.newPassword,
            re_new_password: passwordForm.confirmPassword
        })

        ElMessage.success('密码修改成功，请重新登录')

        // 重置表单
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''

        // 清除token，跳转登录页
        setTimeout(() => {
            user_store.del_token()
            router.push({ name: 'Login' })
        }, 1000)

    } catch (error) {
        console.error('修改密码失败:', error)
        if (error.response && error.response.data) {
            const data = error.response.data
            for (let key in data) {
                ElMessage.error(data[key][0] || '修改密码失败')
            }
        } else {
            ElMessage.error('修改密码失败')
        }
    } finally {
        passwordLoading.value = false
    }
}

// 重置表单
const resetForm = () => {
    fetchUserInfo()
}

// 头像上传成功回调
const handleAvatarSuccess = (response, uploadFile) => {
    user.value.avatar = response.avatar
    userForm.avatar = response.avatar
    ElMessage.success('头像上传成功')
}

// 头像上传前验证
const beforeAvatarUpload = (rawFile) => {
    const type = rawFile.type
    if (type !== 'image/jpeg' && type !== 'image/png') {
        ElMessage.error('头像只能是 JPG 或 PNG 格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像大小不能超过 2MB!')
        return false
    }
    return true
}

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '未知'
    return new Date(dateString).toLocaleDateString('zh-CN')
}

onMounted(() => {
    fetchUserInfo()
})
</script>

<style lang="less" scoped>
.user-info-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.page-header {
    margin-bottom: 30px;
    text-align: center;

    .page-title {
        font-size: 32px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 8px;
    }

    .page-subtitle {
        color: #7f8c8d;
        font-size: 16px;
        margin: 0;
    }
}

.info-card,
.password-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    margin-bottom: 30px;
    overflow: hidden;
}

.card-header {
    padding: 30px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: flex;
    align-items: center;
    gap: 30px;

    .avatar-section {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 15px;

        .user-avatar {
            border: 4px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
        }

        .upload-hint {
            color: rgba(255, 255, 255, 0.9);
            font-size: 12px;
            margin-top: 8px;
        }

        .avatar-uploader {
            :deep(.el-upload) {
                border: none;
                border-radius: 50%;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                transition: all 0.3s ease;

                &:hover {
                    transform: scale(1.05);
                    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
                }
            }
        }
    }

    .user-summary {
        flex: 1;

        .username {
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 20px;
        }

        .user-stats {
            display: flex;
            gap: 30px;

            .stat-item {
                display: flex;
                flex-direction: column;
                gap: 5px;

                .stat-label {
                    font-size: 14px;
                    opacity: 0.8;
                }

                .stat-value {
                    font-size: 18px;
                    font-weight: 500;
                }
            }
        }
    }
}

.password-card .card-header {
    background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;

    .card-title {
        font-size: 24px;
        font-weight: 600;
        margin: 0;
    }

    .card-subtitle {
        font-size: 14px;
        opacity: 0.9;
        margin: 0;
    }
}

.card-body {
    padding: 30px;
}

.user-form,
.password-form {
    max-width: 600px;

    .form-input {
        :deep(.el-input__wrapper) {
            border-radius: 8px;
            transition: all 0.3s ease;

            &:hover {
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            }

            &.is-focus {
                box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
            }
        }

        :deep(.el-textarea__inner) {
            border-radius: 8px;
            transition: all 0.3s ease;

            &:hover {
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            }

            &:focus {
                box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
            }
        }

        :deep(.el-date-editor) {
            border-radius: 8px;
            transition: all 0.3s ease;

            &:hover {
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            }

            &.is-focus {
                box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
            }
        }
    }

    .submit-btn {
        background: linear-gradient(45deg, #667eea, #764ba2);
        border: none;
        border-radius: 8px;
        padding: 12px 30px;
        font-weight: 500;

        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(102, 126, 234, 0.3);
        }
    }
}

.password-form .submit-btn {
    background: linear-gradient(45deg, #11998e, #38ef7d);

    &:hover {
        box-shadow: 0 6px 16px rgba(17, 153, 142, 0.3);
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .user-info-container {
        padding: 15px;
    }

    .card-header {
        flex-direction: column;
        align-items: center;
        text-align: center;
        gap: 20px;
    }

    .user-stats {
        justify-content: center;
    }

    .card-body {
        padding: 20px;
    }
}
</style>